package org.ssm.demo.service.export;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.ssm.demo.Thread.MyTask;
import org.ssm.demo.Thread.MyTaskCall;
import org.ssm.demo.entity.User;
import org.ssm.demo.service.IUserService;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;

import static org.ssm.demo.utils.DomParserUtils.ExportXMLMethod;
import static org.ssm.demo.utils.DomParserUtils.getOneXML;
import static org.ssm.demo.utils.ThreadUtils.getIndex;

/**
 * 配置spring和junit整合，junit启动时加载springIOC容器 spring-test,junit
 */
@RunWith(SpringJUnit4ClassRunner.class)
// 告诉junit spring配置文件
@ContextConfiguration({ "classpath:applicationContext.xml"})
public class ExportTest2 {

    @Autowired
    public IUserService userService;

    @Test
    public void getLimitAndExport() throws ExecutionException, InterruptedException {
        int minSize = 100;//单个线程最小执行数量
        int maxTaskNum = 5;//最大线程数
        int count = 100000;//总数
        int[] indexs = getIndex(count,minSize,maxTaskNum);
//        System.out.print("[");
//        for(int i = 0;i<indexs.length;i++){
//            System.out.print(indexs[i]+",");
//        }
//        System.out.println("]");
        int offset = indexs[1] - indexs[0];
        int endIndex = indexs[indexs.length-2];

        Map<Integer,String> map = new HashMap<Integer,String>();
        List<Future<String>> futures = new ArrayList<>();

        //多线程
        long startTime1 = System.currentTimeMillis();
        ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newCachedThreadPool();
        for(int i=0;i<indexs.length-1;i++){
//            MyTask myTask = new MyTask(indexs[i],offset,endIndex);
//            executor.execute(myTask);
            futures.add(executor.submit(new MyTaskCall(indexs[i],offset,endIndex)));
        }
        executor.shutdown();
        try {//等待直到所有任务完成
            executor.awaitTermination(Long.MAX_VALUE, TimeUnit.MINUTES);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        long endTime1 = System.currentTimeMillis();
        System.out.println("导出程序运行时间：" + (endTime1 - startTime1) + "ms");//输出程序运行时间

        for (int i = 0;i<futures.size();i++) {
//            System.out.println(">>>" + futures.get(i).get());
            map.put(i,futures.get(i).get());
        }

//        long startTime2 = System.currentTimeMillis();
//        getOneXML(map);//合并各个xml文件
//        long endTime2 = System.currentTimeMillis();
//        System.out.println("合并程序运行时间：" + (endTime2 - startTime2) + "ms");//输出程序运行时间
    }

}
